package shop.tbzj.web.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.stat.TableStat.Mode;

import shop.tbzj.entity.TbContentCategory;
import shop.tbzj.service.ContentCategoryService;

@Controller
public class ContentCategoryController {
	@Autowired
	private ContentCategoryService contentCategoryService;

	@RequestMapping(value = { "/" }, method = RequestMethod.GET)
	public String categoryIndex(Model model) {

		List<TbContentCategory> scategoryList = contentCategoryService.findAll();

		List<TbContentCategory> targetList = new ArrayList<>();
		sortList(scategoryList, targetList, 0);
		System.out.println("targetList:" + targetList.toString());
		model.addAttribute("contentCategoryList", targetList);

		return "contentCategory";
	}

	/*
	 * ztree展示
	 */
	@ResponseBody
	@RequestMapping(value="myTree",method=RequestMethod.POST)
	public List<TbContentCategory> myTree(Integer id) {
		 if(id == null){
			 id=0;
		 }
		 List<TbContentCategory> tbContentCategoryList = contentCategoryService.findCategoryByParentId(id);
		return tbContentCategoryList;
	}
	
	//跳转到展示页面
	@RequestMapping("/ztree")
	public String treeIndex(){
		return "ztree";
	}

	@RequestMapping("/test")
	public String testIndex() {
		return "test";
	}
	
	
	@RequestMapping(value="/selectedCategory",method=RequestMethod.POST)
	public String selectedCategor(String contentCategory,Integer id,Model model) {
		//TODO 非空判断
		model.addAttribute("id", id);
		model.addAttribute("contentCategory", contentCategory);
		System.out.println(String.format("选中的类目:%s---%s", contentCategory,id));
		return "submitResult";
	}
	/**
	 * 排序
	 * 
	 * @param sourceList
	 *            数据源集合
	 * @param targetList
	 *            排序后的集合
	 * @param parentId
	 *            当前的父级类目 ID
	 */
	private void sortList(List<TbContentCategory> sourceList, List<TbContentCategory> targetList, Integer parentId) {
		for (TbContentCategory sourceContentCategory : sourceList) {
			if (sourceContentCategory.getParentId().equals(parentId)) {
				targetList.add(sourceContentCategory);
				if (sourceContentCategory.getIsParent()) {
					for (TbContentCategory tbContentCategory : sourceList) {
						if (tbContentCategory.getParentId().equals(sourceContentCategory.getId())) {
							sortList(sourceList, targetList, sourceContentCategory.getId());
							break;
						}
					}
				}
			}
		}
	}

}
